import 'package:easy_chat_app/commons/GlobalStatus.dart';
import 'package:easy_chat_app/commons/db/service/LocalConversationService.dart';
import 'package:easy_chat_app/commons/model/Conversation.dart';
import 'package:easy_chat_app/commons/model/GetChatGroupDetailResultData.dart';
import 'package:easy_chat_app/commons/model/Result.dart';
import 'package:easy_chat_app/commons/utils/HttpUtils.dart';
import 'package:easy_chat_app/commons/utils/RouteUtils.dart';
import 'package:easy_chat_app/commons/widget/ConfirmDialog.dart';
import 'package:easy_chat_app/commons/widget/UserHeadPortrait.dart';
import 'package:easy_chat_app/mobile/constants/MobileAppGlobalConstants.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

class MobileChatGroupInfoPageParams {
  GetChatGroupDetailResultData chatGroupDetail;

  MobileChatGroupInfoPageParams.create({required this.chatGroupDetail});
}

class MobileChatGroupInfoPageChangeNotifier extends ChangeNotifier {
  final Logger logger = Logger();

  GetChatGroupDetailResultData? chatGroupDetail;

  Future<void> reload({required int chatGroupId}) async {
    Result<GetChatGroupDetailResultData?> result =
        await HttpUtils.getChatGroupDetail(chatGroupId);
    if (result.data == null) {
      logger.e("error: $result");
    } else {
      chatGroupDetail = result.data;
    }
    notifyListeners();
  }
}

class MobileChatGroupInfoPage extends StatelessWidget {
  final Logger logger = Logger();

  MobileChatGroupInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    RouteSettings routeSettings = RouteUtils.currentRouteSettings();
    MobileChatGroupInfoPageParams pageParams =
        routeSettings.arguments as MobileChatGroupInfoPageParams;
    return Consumer<AppUserDetailChangeNotifier>(
        builder: (context, appUserDetailChangeNotifier, child) {
      var appUserDetail = appUserDetailChangeNotifier.getAppUserDetail();
      return MultiProvider(
        providers: [
          ChangeNotifierProvider(create: (context) {
            var result = MobileChatGroupInfoPageChangeNotifier();
            return result;
          })
        ],
        builder: (context, child) {
          GetChatGroupDetailResultData chatGroupDetail =
              pageParams.chatGroupDetail;
          logger.i("chatGroupDetail:$chatGroupDetail");
          int userCount = chatGroupDetail.chatGroupUserItemList?.length ?? 0;
          String chatGroupName = chatGroupDetail.name ??
              "群聊(${(chatGroupDetail.chatGroupUserItemList ?? []).length})";
          return Scaffold(
            appBar: AppBar(
              title: Text("群聊信息（$userCount）"),
              centerTitle: true,
              surfaceTintColor: MobileAppGlobalConstants.appBarSurfaceTintColor,
              backgroundColor: MobileAppGlobalConstants.appBarBackgroundColor,
            ),
            body: Container(
              color: const Color.fromRGBO(237, 237, 237, 1),
              height: double.infinity,
              width: double.infinity,
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      color: Colors.white,
                      padding:
                          const EdgeInsets.only(top: 10, left: 10, right: 10),
                      child: GridView.count(
                        crossAxisCount: 5,
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        children: userHeadPortraitWidgetList(
                            context, chatGroupDetail),
                      ),
                    ),
                    GestureDetector(
                      child: Container(
                        alignment: Alignment.center,
                        height: 50,
                        color: Colors.white,
                        child: const Text(
                          "查看更多群成员 >",
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      onTap: () async {
                        await RouteUtils.route2MobileChatGroupUserListPage(
                            chatGroupDetail: pageParams.chatGroupDetail);
                      },
                    ),
                    const SizedBox(height: 8),
                    genChatGroupInfoItem("群聊名称",
                        itemWidget: Text(chatGroupName,
                            style: const TextStyle(
                                fontSize: 16, color: Colors.black))),
                    genChatGroupInfoItem("群二维码",
                        itemWidget: Container(
                          height: 54,
                          alignment: Alignment.centerLeft,
                          child: const Icon(Icons.qr_code),
                        )),
                    genChatGroupInfoItem("我在本群的昵称",
                        itemWidget: Text(appUserDetail.nickname ?? "",
                            style: const TextStyle(fontSize: 16))),
                    const SizedBox(height: 8),
                    GestureDetector(
                      child: Container(
                        height: 50,
                        color: Colors.white,
                        alignment: Alignment.center,
                        child: const Text("退出群聊",
                            style: TextStyle(fontSize: 20, color: Colors.red)),
                      ),
                      onTap: () async {
                        int chatGroupId = chatGroupDetail.id!;
                        _quitChatGroup(context, chatGroupId);
                      },
                    )
                  ],
                ),
              ),
            ),
          );
        },
      );
    });
  }

  List<Widget> userHeadPortraitWidgetList(
      BuildContext context, GetChatGroupDetailResultData chatGroupDetail) {
    final screenSize = MediaQuery.of(context).size;
    double iconSize = (screenSize.width - 40) / 5 - 20;
    List<Widget> userHeadPortraitWidgetList =
        (chatGroupDetail.chatGroupUserItemList ?? []).map((item) {
      return Column(
        children: [
          Container(
              child: UserHeadPortrait.network(
                  size: iconSize,
                  userCode: item.code!,
                  userHeadPortrait: item.headPortrait!,
                  userHeadPortraitStoreType: item.headPortraitStoreType!,
                  circularRadius: 5)),
          Text(
            "${item.nickname}",
            style: const TextStyle(
                fontSize: 12, color: Color.fromRGBO(115, 115, 115, 1)),
          )
        ],
      );
    }).toList();
    int userCount = userHeadPortraitWidgetList.length;
    userHeadPortraitWidgetList =
        userHeadPortraitWidgetList.sublist(0, userCount > 14 ? 14 : userCount);
    userHeadPortraitWidgetList.add(Column(
      children: [
        Expanded(
          child: ImageIcon(
            const AssetImage("images/加号.png"),
            size: iconSize,
            color: const Color.fromRGBO(178, 178, 178, 1),
          ),
        ),
        const Text("")
      ],
    ));
    return userHeadPortraitWidgetList;
  }

  Widget genChatGroupInfoItem(String itemName,
      {bool showBottomBorder = true,
      Widget? itemWidget,
      void Function()? onTap}) {
    itemWidget ??= Container();
    return GestureDetector(
      onTap: onTap,
      child: Container(
        color: Colors.white,
        width: double.infinity,
        height: 55,
        child: Container(
          margin: const EdgeInsets.only(left: 16, right: 16),
          decoration: BoxDecoration(
              border: showBottomBorder
                  ? const Border(
                      bottom:
                          BorderSide(color: Color.fromRGBO(237, 237, 237, 1)))
                  : null),
          child: Row(
            children: [
              Container(
                height: 54,
                alignment: Alignment.centerLeft,
                child: Text(
                  itemName,
                  style: const TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              const Spacer(),
              itemWidget,
              const SizedBox(
                height: 54,
                width: 10,
              ),
              const Icon(Icons.chevron_right_sharp)
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _quitChatGroup(BuildContext context, int chatGroupId) async {
    var confirmResult =
        await ConfirmDialog.show(context, content: const Text("确定要退出群聊?"));
    if (confirmResult) {
      Conversation conversation =
          (await HttpUtils.getConversation(null, chatGroupId)).data!;
      await HttpUtils.quitChatGroup(chatGroupId);
      LocalConversationService.deleteChatHistoryByConversationID(
          conversation.id!);
      GlobalStatus.instance.notify();
      RouteUtils.pop();
      RouteUtils.pop();
    }
  }
}
